package cn._51doit.flink.day02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.redis.RedisSink;
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommand;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommandDescription;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisMapper;
import org.apache.flink.util.Collector;

/**
 *  将wordcount的结果写入到redis中
 */
public class RedisSink1 {

    public static void main(String[] args) throws Exception {

        //创建本地指定的Env，并且带WebUI的
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port", 8081);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(configuration);
        //1.创建执行环境
        //StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //2.调用Evn的Source方法，创建抽象数据集
        DataStreamSource<String> lines = env.socketTextStream(args[0], Integer.parseInt(args[1]));
        //3.调用Transformation（s）
        SingleOutputStreamOperator<Tuple2<String, Integer>> res = lines.flatMap(new LineSplitor())
                .keyBy(0)
                .sum(1);

        //redis的配置
        FlinkJedisPoolConfig conf = new FlinkJedisPoolConfig.Builder()
                .setHost("node-3.51doit.cn")
                .setDatabase(3)
                .setPassword("123456")
                .build();
        //传入redis sink和配置mapper
        res.addSink(new RedisSink<Tuple2<String, Integer>>(conf, new RedisWordCountMapper()));

        //5.执行并挂起
        env.execute();


    }

    public static class LineSplitor implements FlatMapFunction<String, Tuple2<String, Integer>> {

        @Override
        public void flatMap(String in, Collector<Tuple2<String, Integer>> collector) throws Exception {
            String[] words = in.split(" ");
            for (String word : words) {
                collector.collect(Tuple2.of(word, 1));
            }
        }
    }

    /**
     * Redis的映射类，决定以何种方式写入到Redis中，那个字段作为key，哪个字段作为value
     * 泛型为输入到Sink中的数据类型
     */
    public static class RedisWordCountMapper implements RedisMapper<Tuple2<String, Integer>> {

        /**
         * 决定以何种方式写入到redis中
         * @return
         */
        @Override
        public RedisCommandDescription getCommandDescription() {
            //大key -> (小key， 小value)
            return new RedisCommandDescription(RedisCommand.HSET, "word-count");
        }

        /**
         * 设置小key的内容
         * @param data
         * @return
         */
        @Override
        public String getKeyFromData(Tuple2<String, Integer> data) {
            return data.f0;
        }

        /**
         * 设置小value的内容
         * @param data
         * @return
         */
        @Override
        public String getValueFromData(Tuple2<String, Integer> data) {
            return data.f1.toString();
        }
    }
}
